package bll

import (
	"errors"
	"fmt"
	"jgt-oper/src/model"
	"jgt-oper/src/schema"
	"sync"
)

// Parking 停车位管理
type Parking struct {
	sync.RWMutex
	ParkingModel model.IParking `inject:"IParking"`
}

// Create 创建停车场节点
func (a *Parking) Create(item *schema.Parking) error {
	return a.ParkingModel.Create(item)
}

// Get 获取节点
func (a *Parking) Get(recordID string) (*schema.Parking, error) {
	return a.ParkingModel.Get(recordID)
}

// Update 更新、删除
func (a *Parking) Update(recordID string, info map[string]interface{}) error {
	return a.ParkingModel.Update(recordID, info)
}

// QueryIndex 查询第一级节点列表
func (a *Parking) QueryIndex(nodeType int) ([]*schema.Parking, error) {
	return a.ParkingModel.QueryIndex(nodeType)
}

// QueryChildrenNodes 子节点
func (a *Parking) QueryChildrenNodes(recordID string) ([]*schema.Parking, error) {
	return a.ParkingModel.QueryChildrenNodes(recordID)
}

// GetLevelCode 获取分级码
func (a *Parking) GetLevelCode(parentID string) (string, error) {
	a.Lock()
	defer a.Unlock()

	items, err := a.ParkingModel.QueryParentNodes(parentID)
	if err != nil {
		return "", err
	} else if len(items) == 0 {
		if parentID == "" {
			return "01", nil
		}
		item, verr := a.Get(parentID)
		if verr != nil {
			return "", verr
		} else if item == nil {
			return "", errors.New("无效的上级")
		}
		return item.LevelCode + "01", nil
	}

	levelCode := items[0].LevelCode
	root := levelCode[:len(levelCode)-2]
	toValue := func(i int) string {
		if i < 10 {
			return fmt.Sprintf("%s0%d", root, i)
		}
		return fmt.Sprintf("%s%d", root, i)
	}

	for i, l := 1, len(items); i < 100; i++ {
		code := toValue(i)
		if i <= l &&
			items[i-1].LevelCode == code {
			continue
		}
		return code, nil
	}

	return "", errors.New("获取分级码发生错误")
}
